package com.qf.contller;

import com.qf.config.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author lyx
 * @date 2022/7/11 17:31
 * 模拟秒杀问题
 */
@RestController
public class SecondKillController {

    //1.准备库存商品
    public static HashMap<String, Integer> itemStork = new HashMap<String, Integer>();

    //2.准备商品订单
    public static HashMap<String, Integer> itemOrder = new HashMap<String, Integer>();

    @Autowired
    private CuratorFramework cf;

    @Autowired
    private RedisLockUtil rul;

    static {

        //商品数量
        itemStork.put("牙刷", 10000);

        //订单数量
        itemOrder.put("牙刷", 0);

    }

    @GetMapping("/kill")
    public String kill(String item) throws Exception {
        //=========================加zookeeper锁======================
     //   InterProcessMutex lock = new InterProcessMutex(cf, "/lock");
        //=========================加zookeeper锁======================
       // if (lock.acquire(1, TimeUnit.SECONDS)) {

        //========================Redis加锁========================
        if(rul.lock(item, String.valueOf(System.currentTimeMillis()),1)){
            //减库存
            Integer count = itemStork.get("牙刷");
            if (count <= 0) {
                return "库存不足";
            }
            itemStork.put(item, count - 1);

            //增加订单
            itemOrder.put(item, itemOrder.get(item) + 1);
            //=========================加zookeeper锁======================
          //  lock.release();
            //=========================加zookeeper锁======================
            rul.unlock(item);
            return "抢购成功剩余数量" + itemStork.get(item) + "订单数量" + itemOrder.get(item);
        } else {

            return "库存不足";
        }


    }


}
